package com.ideaaedi.shardingdynamictable.util;

import com.ideaaedi.shardingdynamictable.entity.bo.DatasourceArgs;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.TreeSet;

/**
 * (non-javadoc)
 *
 * @author JustryDeng
 * @since 2022/10/7 0:01:54
 */
public final class DatabaseUtil {
    
    /**
     * 执行sql
     *
     * @param datasourceArgs
     *            数据源参数
     * @param sqlList
     *            待执行的sql集合
     */
    public static void executeSql(DatasourceArgs datasourceArgs, List<String> sqlList) {
        try (Connection connection = DriverManager.getConnection(datasourceArgs.getJdbcUrl(), datasourceArgs.getUsername(), datasourceArgs.getPassword())) {
            try (Statement statement = connection.createStatement()) {
                connection.setAutoCommit(false);
                for (String sql : sqlList) {
                    statement.execute(sql);
                }
                connection.commit();
            } catch (Exception ex) {
                connection.rollback();
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    
    /**
     * 根据表名前缀获取表名
     *
     * @param datasourceArgs
     *            数据源参数
     * @param prefix
     *            表名前缀
     * @return  prefix
     */
    public static TreeSet<String> obtainTableNameByPrefix(DatasourceArgs datasourceArgs, String prefix) {
        TreeSet<String> tableNames = new TreeSet<>();
        try (Connection connection = DriverManager.getConnection(datasourceArgs.getJdbcUrl(),
                datasourceArgs.getUsername(), datasourceArgs.getPassword());
             Statement statement = connection.createStatement()) {
            try (ResultSet rs = statement.executeQuery("SHOW TABLES like '" + prefix + "%'")) {
                while (rs.next()) {
                    tableNames.add(rs.getString(1));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return tableNames;
    }
}
